$(function() {
    //表格实例化
    var clusterTable = null;
    var opts = {
        targetId: "exptTable",
        templateId: "tableSaleExpt",
        settings: {
            url: DI.commCluster,
            ajaxType: "json",
            sourceInterface: {
                INum: "totalSize",
                IData: "records"
            },
            paginationIndexName: {
                "peerpageRows": "pageSize",
                "currentPage": "pageNo"
            },
            searchParam: {
                "pageNo": 1,
                "pageSize": 10,
                "commInfo": ""
            }
        },
        customFuncs: {
        }
    };

    //主流程对象
    var mainCtrl = avalon.define({
        $id: "mainController",
        regionCode: "",
        selRegion: "", //显示的值
        allRegion: [], //先记录下来模糊查询时需要用到
        branchCode: "",
        allBranch: [],
        commInfo: "", //商品编码/名称
        searchCluster: 0, //查询后簇的值
        curRegion: "", //查询后所对应的大区
        curBranch: "", //查询后所对应的分公司
        dataLen: 0, //判断导出是否置灰 0置灰
        clickSearchParam: {
            commInfo: ""
        },
        search: function() {
            mainCtrl.clickSearchParam = {
                commInfo: mainCtrl.commInfo
            };
            mainCtrl.dataLen = 0;
            var searchParam = {
                "pageNo": 1,
                "pageSize": 10,
                "commInfo": mainCtrl.commInfo
            };
            clusterTable.search(searchParam);
            checkDataLen();
        },
        toExport: function(idx) {
        	var exportURL = DI.exptCommCluster + "?index=" + idx;
            if(mainCtrl.commInfo) {
                exportURL += "&commInfo=" + mainCtrl.commInfo;
            }
//            window.location = exportURL
            window.open(exportURL);
        },
        exportPop: function() {
            if(mainCtrl.dataLen == 0) {
                return;
            }
            //如果总数据 小于 获取的导出限制值 说明数据量很小，直接导出 
            if(mainCtrl.dataLen <= popCtrl.gotNum) {
                mainCtrl.toExport(1);
                return;
            }
            //0代表没有取过导出限制值，如果取过就不用再去取了
            if(popCtrl.gotNum == 0) {
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: DI.queryExptCSVLimit,
                    success: function(data) {
                        var num = data.data,
                            exportCount = Math.ceil(mainCtrl.dataLen / num),
                            countList = [],
                            startNum = 1;
                        popCtrl.gotNum = num;
                        //如果总数据 小于 获取的导出限制值 说明数据量很小，直接导出 
                        if(mainCtrl.dataLen <= popCtrl.gotNum) {
                            mainCtrl.toExport(1);
                            return;
                        }
                        for(var i = 0; i < exportCount; i++) {
                            var endNum = startNum + (num - 1);
                            if(endNum > mainCtrl.dataLen) {
                                endNum = mainCtrl.dataLen;
                            }
                            countList.push(startNum + "~" + endNum);
                            startNum = endNum + 1;
                        }
                        popCtrl.exportCountList = countList;
                        $("#popup_cnt").show();
                    },
                    error: function(err) {
                        console.log(err);
                    }
                });
            } else {
                $("#popup_cnt").show();
            }
        },
        importXls: function() {
        	// 展示上传弹出框
        	$("#popup_import").show();
        }
    });
    var popCtrl = avalon.define({
        $id: "popController",
        confirmType: "del",
        delCommObj: "",
        gotNum: 0, //判断是否获取过导出限制值
        exportCountList: [],
        countIdx: 1,
        selCount: function() {
            popCtrl.countIdx = $(this).index() + 1;
            $(this).addClass("sel").siblings(".e-number").removeClass("sel");
        },
        exportList: function() {
            mainCtrl.toExport(popCtrl.countIdx);
        },
        confirmSure: function() {
        },
        uploadFile: function() {
        	var inputFile = '#file';
        	if (!$(inputFile).val()) {
        		return;
        	}
        	var data = new FormData();
        	data.append('firstExcel', $(inputFile)[0].files[0]);
        	$("#popup_import").hide();
        	$('.loadData').show();
        	$.ajax({
        		url : DI.batchImportCluster,
        		type : 'POST',
        		data : data,
        		dataType : 'json',
        		processData : false,
        		contentType : false
        	}).done(function(data) {
        		if (data.retFlag == 1) {
        			PLATFORM.showTips("success", "导入成功");
        			//window.location.href = 'clusterCommManage.html';
        			clusterTable.refresh();
        		} else {
        			var message = data.errorMessage;
        			if (message) {
        				PLATFORM.showTips("error", data.errorMessage);
        			} else {
        				var errorList = data.data;
        				 PLATFORM.showTips("error", errorList);
        			}
        		}
        	}).fail(function() {
        		PLATFORM.showTips("error", "导入失败");
        	}).always(function() {
        		$('#file').val('');
        		$('.loadData').hide();
        	});
        }
    });

    //检查列表长度，如果长度大于0了，需要显示导出按钮，和当前大区分公司等信息
	function checkDataLen() {
		var intervalSource = setInterval(function() {
            var dataLen = clusterTable.table.total;
            if(dataLen > 0) {
                clearInterval(intervalSource);
                mainCtrl.dataLen = clusterTable.table.returnData.data.exportSize;
                mainCtrl.curRegion = clusterTable.table.sources[0].regionName;
                mainCtrl.curBranch = clusterTable.table.sources[0].branchName;
            }
        }, 100);
	}
    // 根据大区查公司
    function getBranchByCode(regionCode) {
        var allBranchList = mainCtrl.allBranch,
            allBranchLen = allBranchList.length,
            newBranch = [];
        if(regionCode == "") {
            newBranch = allBranchList;
        } else {
            for(var i = 0; i < allBranchLen; i++) {
                if(allBranchList[i].pid == regionCode) {
                    newBranch.push({
                        "id": allBranchList[i].id,
                        "text": allBranchList[i].text,
                        "pid": regionCode
                    });
                }
            }
        }

    }
    //根据选择的分公司推出对应的大区
    function getRegionBybcode(pid) {
        var allRegionList = mainCtrl.allRegion,
            allRegionLen = allRegionList.length,
            newRegion = [];
        if(pid) {
            var regionObj = "";
            for(var i = 0; i < allRegionLen; i++) {
                var regionid = allRegionList[i].id;
                if(regionid == pid) {
                    var regionTxt = allRegionList[i].text,
                        regionName = regionid + "-" + regionTxt;
                    regionObj = {
                        "id": regionid,
                        "name": regionName
                    }
                    break;
                }
            }
            if(regionObj != "") {
                magicRegion.setSelection(regionObj)
            }
        }
    }

    //Url里面返回了查询条件回来
    var urlParams = PLATFORM.getUrlArgs();
    mainCtrl.commInfo = urlParams.commInfo?urlParams.commInfo:"";

    // 绘制表格
    clusterTable = SwiftUI.swiftTable.getInstance(opts);
    
    checkDataLen();
    
    avalon.scan();
});
